#include "competitionmanager.h"
#include "ui_competitionmanager.h"
#include "competition/completed/createcompletedcompetition.h"

#include <QMenu>

CompetitionManager::CompetitionManager(SystemController *systemController, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CompetitionManager)
{
    ui->setupUi(this);
    this->systemController = systemController;
    beforeSelectedRowDistance = -1;

    //Creates the needed Model
    //QSqlDatabase db = QSqlDatabase::database("sqlDb", false);
    QSqlDatabase db = QSqlDatabase::cloneDatabase(QSqlDatabase::database("sqlDb", false), "sqlDbCompetitionManager");
    db.setDatabaseName(this->systemController->getDatabasePath());
    db.open();
    this->completedCompetitionModel = new CompetitionModel(this->systemController ,this, db);
    this->completedCompetitionModel->setTable("competition");

    this->completedCompetitionModel->setHeaderData(CompetitionModel::NAME_COLUMN, Qt::Horizontal, tr("Name"));
    this->completedCompetitionModel->setHeaderData(CompetitionModel::CITY_COLUMN, Qt::Horizontal, tr("City"));
    this->completedCompetitionModel->setHeaderData(CompetitionModel::DATE_COLUMN, Qt::Horizontal, tr("Date"));
    this->completedCompetitionModel->setHeaderData(CompetitionModel::CONTACT_MAIL_COLUMN, Qt::Horizontal, tr("Mail"));
    this->completedCompetitionModel->setHeaderData(CompetitionModel::CONTACT_WEB_COLUMN, Qt::Horizontal, tr("Web"));

    //Set the Model and hide needed Collumns
    ui->tableView->setModel(this->completedCompetitionModel);
    ui->tableView->hideColumn(CompetitionModel::ID_COLUMN);

    //Prepare the DistanceModel
    this->distanceModel = new DistanceModel(this->systemController, this, db);
    this->distanceModel->setTable("trackEvent");

    this->distanceModel->setHeaderData(DistanceModel::LENGTH_COLUMN, Qt::Horizontal, tr("Length"));
    this->distanceModel->setHeaderData(DistanceModel::COMMENT_COLUMN, Qt::Horizontal, tr("Comment"));
    this->distanceModel->setHeaderData(DistanceModel::MIN_AGE_COLUMN, Qt::Horizontal, tr("minimum Age"));
    this->distanceModel->setHeaderData(DistanceModel::MAX_AGE_COLUMN, Qt::Horizontal, tr("maximum Age"));

    //Prepare the distance Table
    ui->tableView_2->setModel(this->distanceModel);
    ui->tableView_2->hideColumn(DistanceModel::ID_COLUMN);
    ui->tableView_2->hideColumn(DistanceModel::COMPETITION_ID_COLUMN);

    //Connect the needed Slots
    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showRightClickMenuCompletedCompetitions(QPoint)));
    connect(ui->tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(refreshDistanceView()));


    //Fill needed Tables / Widgets
    this->refreshView();
    this->fillComboBox();


}

CompetitionManager::~CompetitionManager()
{
    delete this->completedCompetitionModel;
    delete ui;
}

//////////////////////////////////////////////////
//Functions for allready completed Competitions//
////////////////////////////////////////////////

//Functions for Competitions
////////////////////////////
/*!
    \fn refreshView
    Function to refresh the View
  */
void CompetitionManager::refreshView()
{
    if (!this->completedCompetitionModel->select())
    {
        this->systemController->showErrorDialog(this, tr("Error while loading data"), tr("While loading the data an error occoured"),
                                                this->completedCompetitionModel->lastError().text());
    }
    ui->tableView->resizeColumnsToContents();
    this->completedCompetitionModel->sort(CompetitionModel::DATE_COLUMN, Qt::DescendingOrder);
}

/*!
  \fn on_pushButton_clicked
  Function which called when the add Competition Button is clicked
  */
void CompetitionManager::on_pushButton_clicked()
{
    CreateCompletedCompetition compDlg(this->systemController, this);

    if (QDialog::Accepted == compDlg.exec())
    {
        //If Dialog result ok, create the SqlStatement
        QString stmt;
        stmt = "INSERT INTO competition(\"cId\", \"name\", \"city\", \"date\", \"contactMail\", \"contactWeb\") VALUES(NULL,\"" +
                compDlg.getName() +
                "\", \"" + compDlg.getCity() +
                "\", \"" + compDlg.getDate().toString("yyyy-MM-dd") +
                "\", \"" + compDlg.getMail() +
                "\", \"" + compDlg.getWeb() +
                "\");";

        //Execute the SqlStatement
        SqlLite db;
        if (!db.connect(this->systemController->getDatabasePath()))
            this->systemController->showErrorDialog(this, tr("Error while adding the Competition"), tr("While adding the Competition an error occoured"),
                                                    db.getLasterErrorMessage());
        else
        {
            if (!db.executeCommand(stmt))
                this->systemController->showErrorDialog(this, tr("Error while adding the Competition"), tr("While adding the Competition an error occoured"),
                                                        db.getLasterErrorMessage());
            else
            {
                refreshView();
                //Select right Row
                int id = db.getLastIndex();
                int rows = this->completedCompetitionModel->rowCount();
                int affectedRow = -1;
                for (int i=0; i < rows; i++)
                {
                    if (this->completedCompetitionModel->data(this->completedCompetitionModel->index(i, CompetitionModel::ID_COLUMN)).toInt()
                            == id)
                        affectedRow = i;
                }
                if (affectedRow != -1)
                    ui->tableView->selectRow(affectedRow);
                    ui->tableView->scrollTo(ui->tableView->selectionModel()->currentIndex());
            }
        }
        db.disconnect();


    }
    compDlg.close();
}

/*!
  \fn on_pushButton_2_clicked
  Function which called when the remove Competition Button is clicked
  */
void CompetitionManager::on_pushButton_2_clicked()
{
    int row = ui->tableView->selectionModel()->currentIndex().row();
    if (row != -1)
    {
        QString questionString = tr("Are you sure to delete Competition \"");
        questionString.append(this->completedCompetitionModel->data(this->completedCompetitionModel->index(row, CompetitionModel::NAME_COLUMN)).toString());
        questionString.append("\" ?");

        if (QMessageBox::question(this, tr("Sure to delete the Competition"), questionString,
                              QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
        {
            QString id = this->completedCompetitionModel->data(this->completedCompetitionModel->index(row, CompetitionModel::ID_COLUMN)).toString();

            //If Dialog result ok, create the SqlStatement
            QString stmt;
            stmt = "DELETE FROM competition WHERE cId=" + id;

            //Execute the SqlStatement
            SqlLite db;
            if (!db.connect(this->systemController->getDatabasePath()))
                this->systemController->showErrorDialog(this, tr("Error while removing the Competition"), tr("While removing the Competition an error occoured"),
                                                        db.getLasterErrorMessage());
            else
            {
                if (!db.executeCommand(stmt))
                    this->systemController->showErrorDialog(this, tr("Error while removing the Competition"), tr("While removing the Competition an error occoured"),
                                                            db.getLasterErrorMessage());
                else
                    refreshView();
            }
            db.disconnect();
        }
    }
}
/*!
  \fn showRightClickMenuCompletedCompetitions
  Shows the right click menu for completed Competitions
  */
void CompetitionManager::showRightClickMenuCompletedCompetitions(const QPoint &pos)
{
    QMenu menu;
    //qDebug() << "Spalte: " <<ui->tableView->selectionModel()->currentIndex().column() << "Zeile: " <<ui->tableView->selectionModel()->currentIndex().row();
    menu.addAction(QIcon(":/competition/16/list-add-5.png"), tr("Add Competition"), this, SLOT(on_pushButton_clicked()));
    menu.addAction(QIcon(":/competition/16/list-remove-4.png"), tr("Remove Competition"), this, SLOT(on_pushButton_2_clicked()));
    menu.exec(QCursor::pos());
}



//Functions for Distances
/////////////////////////

/*!
  \fn fillComboBox
  Function which fill the ComboBox with values
  */
void CompetitionManager::fillComboBox()
{

}

/*!
  \fn Refreshes the Distnaces View
  */
void CompetitionManager::refreshDistanceView()
{
    //Get the selected Row
    int row = ui->tableView->selectionModel()->currentIndex().row();
    qDebug() << "row:" << row;
    if ((row == this->beforeSelectedRowDistance) || (row == -1))
        return;

    this->beforeSelectedRowDistance = row;
    //Get the cId
    QString cId = this->completedCompetitionModel->data(this->completedCompetitionModel->index(row, CompetitionModel::ID_COLUMN)).toString();

    this->distanceModel->setFilter("cId=" + cId);

    if (!this->distanceModel->select())
    {
        this->systemController->showErrorDialog(this, tr("Error while loading data"), tr("While loading the data an error occoured"),
                                                this->completedCompetitionModel->lastError().text());
    }
    ui->tableView->resizeColumnsToContents();
    this->distanceModel->sort(DistanceModel::LENGTH_COLUMN, Qt::DescendingOrder);
}


/*!
  \fn on_pushButton_4_clicked
    Called when add Competition Button is clicked
  */
void CompetitionManager::on_pushButton_4_clicked()
{
    /*//Check if a competition is selected
    int row = ui->tableView->selectionModel()->currentIndex().row();

    if (row == -1)
    {
        QMessageBox::warning(this, tr("Please select a Competition"), tr("Please select a Competition to add the distance"));
        return;
    }

    //Check if a Length is seted
    if (ui->spinBox->value() == 0)
    {
        QMessageBox::warning(this, tr("Please specify the length"), tr("Please specify the Length of this Distance"));
        return;
    }

    //Get the needed Values
    QString cId = this->completedCompetitionModel->data(this->completedCompetitionModel->index(row, CompetitionModel::ID_COLUMN)).toString();
    QString length = QString::number(ui->spinBox->value());
    QString minAge = QString::number(ui->minAgeSpinBox->value());
    QString maxAge = QString::number(ui->maxAgeSpinBox->value());
    QString comment = ui->comboBox->currentText().trimmed();
    QString commentItemData = ui->comboBox->itemData(ui->comboBox->currentIndex()).toString();
    QString stmt = "";

    //Check if it needed to add the new Comment to the table
    if ((comment != "") && (commentItemData == ""))
    {
        stmt = "INSERT INTO comment(\"commentId\", \"name\") VALUES(NULL,\"" + comment +"\");";

        //Execute the SqlStatement
        SqlLite db;
        if (!db.connect(this->systemController->getDatabasePath()))
            this->systemController->showErrorDialog(this, tr("Error while adding the Distance"), tr("While adding the Distance an error occoured"),
                                                    db.getLasterErrorMessage());
        else
        {
            if (!db.executeCommand(stmt))
                this->systemController->showErrorDialog(this, tr("Error while adding the Distance"), tr("While adding the Distance an error occoured"),
                                                        db.getLasterErrorMessage());
            else
                commentItemData = QString::number(db.getLastIndex());
        }
    }

    //Insert the Distance

    stmt = "INSERT INTO trackEvent(\"tId\", \"cId\", \"length\", \"minAge\", \"maxAge\", \"commentId\") VALUES(NULL,\"" +
            cId +
            "\", \"" + length +
            "\", \"" + minAge +
            "\", \"" + maxAge +
            "\", \"" + commentItemData +
            "\");";

    //Execute the SqlStatement
    SqlLite db;
    if (!db.connect(this->systemController->getDatabasePath()))
        this->systemController->showErrorDialog(this, tr("Error while adding the Distance"), tr("While adding the Distance an error occoured"),
                                                db.getLasterErrorMessage());
    else
    {
        if (!db.executeCommand(stmt))
            this->systemController->showErrorDialog(this, tr("Error while adding the Distance"), tr("While adding the Distance an error occoured"),
                                                    db.getLasterErrorMessage());
        else
            refreshDistanceView();
    }

    db.disconnect();

    fillComboBox();
    this->beforeSelectedRowDistance = -1;
    refreshDistanceView();
    ui->spinBox->setValue(0);
    ui->minAgeSpinBox->setValue(0);
    ui->maxAgeSpinBox->setValue(0); */
}
